package com.example.my_bookkeeping.data.manager;

import com.example.my_bookkeeping.data.user.User;

import java.util.ArrayList;
import java.util.HashMap;

public class UserManager extends Manager {
    // 使用单例设计模式，在本类中对用户信息进行管理
    private static final UserManager instance = new UserManager();
    private final HashMap<Long, User> userBank = new HashMap<>();
    private long currentUserId = 0;

    private UserManager() {
        userBank.put(0L, new User("系统用户", "系统用户", 0));
    }

    public static UserManager getInstance() {
        return instance;
    }

    private boolean isUserNoExist(long currentUserId) {
        return userBank.isEmpty() || userBank.get(currentUserId) == null;
    }

    public void add(User user) {
        userBank.put(user.getId(), user);
        notifyObservers();
    }

    public void update(String name, String remark, double amount) {
        // 接受参数字段，修改当前用户信息
        if (isUserNoExist(currentUserId))
            return;
        User user = userBank.get(currentUserId);
        if (user != null) {
            user.setName(name);
            user.setRemark(remark);
            user.setAmount(amount);
        }
        notifyObservers();
    }

    public void switchUser(User user) {
        if (isUserNoExist(user.getId()))
            return;
        currentUserId = user.getId();
    }

    public User getCurrentUser() {
        if (isUserNoExist(currentUserId))
            return null;
        return userBank.get(currentUserId);
    }

    public ArrayList<User> getAll() {
        return new ArrayList<>(userBank.values());
    }

    public void delete(User user) {
        userBank.remove(user.getId());
        notifyObservers();
    }

    // 清除所有用户数据，重置默认用户
    public void reset() {
        userBank.clear();
        User.reSet();
        userBank.put(0L, new User("系统用户", "系统用户", 0));
    }
}
